package com.code.classsystem.controller;

import com.code.core.entity.ResponseResult;
import com.code.core.util.ResponseResultUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/compiler")
public class CompilerController {

    @PostMapping("/compile")
    public ResponseResult compileJava(@RequestBody String payload) throws IOException {
        String javaCode = "asd";

        // 调用编译工具编译 Java 代码
        String command = "javac -d . -classpath . " + javaCode;
        Process process = Runtime.getRuntime().exec(command);

        // 获取编译结果
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder output = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line).append("\n");
        }

        // 返回编译结果给前端
        Map<String, String> response = new HashMap<>();
        response.put("output", output.toString());
        return ResponseResultUtil.renderSuccess(response);
    }
}